package com.leoman.spinningmachine.http;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.leoman.helper.util.JsonKit;
import com.leoman.spinningmachine.util.QuitUtil;

import java.lang.reflect.Type;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by spurs on 16/9/13.
 * 接口数据回调
 */
public class APICallback implements Callback<Object> {

    private final static String TAG = APICallback.class.getSimpleName();

    private Integer tag;

    private OnResponseListener mOnResponseListener;

    private Type objectType;

    /**
     * 返回不带list数据
     */

    public APICallback(OnResponseListener onResponseListener, Integer tag) {
        this.mOnResponseListener = onResponseListener;
        this.tag = tag;
    }

    /**
     * 处理list泛型数据结构
     *
     */
    public APICallback(OnResponseListener onResponseListener, Type objectType, Integer tag) {
        this.mOnResponseListener = onResponseListener;
        this.objectType = objectType;
        this.tag = tag;
    }

    /**
     * 处理gson转换时默认将Integer转换成Double
     */
    Gson gson = new GsonBuilder().
            registerTypeAdapter(Double.class, new JsonSerializer<Double>() {

                @Override
                public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) {
                    if (src == src.longValue())
                        return new JsonPrimitive(src.longValue());
                    return new JsonPrimitive(src);
                }
            })
            .disableHtmlEscaping()
            .create();

    @Override
    public void onResponse(Call<Object> call, Response<Object> response) {
        String JSON_BACK = gson.toJson(response.body());
        Log.e("JSON_BACK", "返回数据 = " + JSON_BACK);
        if (response.code() == 200) {
            APIResponse apiResponse = JsonKit.parse(JSON_BACK, APIResponse.class);
            /*success*/
            if (apiResponse.code.equals("0")) {
                if (apiResponse.data == null)
                    apiResponse.data = new MapData();
                if (objectType != null) {
                    String string = gson.toJson(apiResponse.data.list);
                    apiResponse.data.list = gson.fromJson(string, objectType);
                }
                mOnResponseListener.OnSuccessData(apiResponse, tag);
            } else if (apiResponse.code.equals("999")) {
                mOnResponseListener.OnErrorData("服务器繁忙，请稍后再试", tag);
            } else if (apiResponse.code.equals("100")) {
                QuitUtil.quit(false);
                mOnResponseListener.OnErrorData(apiResponse.code, tag);
            }else {
                mOnResponseListener.OnErrorData(apiResponse.message, tag);
            }
        } else {
            Log.e("response.code()==", response.code() + "  url==" + response.raw().networkResponse().request().url().url());
            mOnResponseListener.OnFailureData(String.valueOf(response.code()), tag);
        }

        /*关闭请求*/
        if (call != null)
            call.cancel();

    }

    @Override
    public void onFailure(Call<Object> call, Throwable t) {
        Log.e(TAG, "Error : " + t);
        mOnResponseListener.OnFailureData(t.getMessage(), tag);

         /*关闭请求*/
        if (call != null)
            call.cancel();
    }


    public interface OnResponseListener {

        void OnFailureData(String error, Integer tag);

        void OnSuccessData(APIResponse apiResponse, Integer tag);

        void OnErrorData(String code, Integer tag);
    }

    public void setOnResposeListener(OnResponseListener onResponseListener) {
        mOnResponseListener = onResponseListener;
    }

}
